package collector.parsers;

import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import collector.support.URLHandler;

public class StockMarketSubListFinder extends Thread implements Iterable<String> {
	private URLHandler urlHandler;
	private HashMap<String, String> matches;
	private String market;
	private Semaphore parsing;
	private String url;
	private String list;

	public StockMarketSubListFinder(String market, String list) {
		parsing = new Semaphore(1);
		try {
			parsing.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.market = market;
		this.list = list;
		this.url = "https://www.avanza.se/aza/aktieroptioner/kurslistor/kurslistor.jsp?cc="
			+ market + "&lkey=" + list;
		this.start();
	}

	public void run() {
		urlHandler = URLHandler
				.create(url);
		matches = new HashMap<String, String>();
		String content = urlHandler.getContent();
		Pattern delimiterPattern = Pattern
				.compile(
						"cc="+market+"&lkey="+list+"&delimiters=([^\']*)'>", //"<select name=\"lkey\".*?>(.*?<option.*?value=\"([^\"]*)\".*?>([^<]*)</option>.*?)?</select>",
						Pattern.CASE_INSENSITIVE);
		Matcher delimiterMatcher = delimiterPattern.matcher(content);
		String delimiterString = null;
		try {
			while (delimiterMatcher.find()) {
				delimiterString = delimiterMatcher.group(1).trim();
				//System.out.println(delimiterString);
				matches.put(delimiterString, delimiterString);
				//debug
				//break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		parsing.release();
	}

	public HashMap<String, String> getSubLists() {
		try {
			parsing.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		HashMap<String, String> result = matches;
		parsing.release();
		return result;
	}

	@Override
	public Iterator<String> iterator() {
		return getSubLists().keySet().iterator();
	}
}
